<template>
    <a-spin :spinning="confirmLoading">
        <j-form-container :disabled="formDisabled">
            <!-- 主表单区域 -->
            <a-form :form="form" slot="detail">
                <a-row>
                    <a-col :span="24">
                        <a-form-item label="单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['orderNo']" placeholder="请输入单号"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="所属生产线" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-dict-select-tag dictCode="basic_production_line, name, name"
                                placeholder="请选择所属生产线" :trigger-change="true"
                                v-decorator="['productionLine', validatorRules.productionLine]"></j-dict-select-tag>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="计划生产日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-date placeholder="请选择计划生产日期"
                                v-decorator="['productDay', validatorRules.productDay]"
                                :trigger-change="true" style="width: 100%" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="计划开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-time placeholder="请选择计划开始时间"
                                v-decorator="['startTime', validatorRules.startTime]"
                                :trigger-change="true" style="width: 100%" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="计划结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-time placeholder="请选择计划结束时间"
                                v-decorator="['endTime', validatorRules.endTime]"
                                :trigger-change="true" style="width: 100%" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="需求物料时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <j-time placeholder="请选择需求物料时间"
                                v-decorator="['needTime', validatorRules.needTime]"
                                :trigger-change="true" style="width: 100%" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24" v-if="model.id">
                        <a-form-item label="总体积" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['volume']" placeholder="请输入总体积"
                                disabled></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['remarks']" placeholder="请输入备注"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24" v-if="model.id">
                        <a-form-item label="订单发布时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['releaseTime']" placeholder="请输入订单发布时间"
                                disabled></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24" v-if="model.id">
                        <a-form-item label="配货完成时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                            <a-input v-decorator="['distributionTime']" placeholder="请输入配货完成时间"
                                disabled></a-input>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </j-form-container>
        <!-- 子表单区域 -->
        <a-tabs v-model="activeKey" @change="handleChangeTabs">
            <a-tab-pane tab="制品明细" :key="refKeys[0]" :forceRender="true">
                <j-editable-table :ref="refKeys[0]" :loading="planProductsDetailTable.loading"
                    :columns="planProductsDetailTable.columns" @valueChange="onValueChange"
                    :dataSource="planProductsDetailTable.dataSource" :maxHeight="300"
                    :disabled="formDisabled" :rowNumber="true" :rowSelection="true"
                    :actionButton="true" />
            </a-tab-pane>
            <a-tab-pane tab="部品明细" :key="refKeys[1]" :forceRender="true" :disabled="!model.status">
                <j-editable-table :ref="refKeys[1]" :loading="planPartsDetailTable.loading"
                    :columns="planPartsDetailTable.columns"
                    :dataSource="planPartsDetailTable.dataSource" :maxHeight="300"
                    :disabled="formDisabled" :rowNumber="true" :rowSelection="true"
                    :actionButton="true" />
            </a-tab-pane>
        </a-tabs>
        <a-row v-if="showFlowSubmitButton"
            style="text-align: center;width: 100%;margin-top: 16px;"><a-button @click="handleOk">提
                交</a-button></a-row>
    </a-spin>
</template>

<script>

import pick from 'lodash.pick'
import { getAction } from '@/api/manage'
import { FormTypes, getRefPromise } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { validateDuplicateValue } from '@/utils/util'

export default {
    name: 'PlanProductionForm',
    mixins: [JEditableTableMixin],
    components: {
    },
    data() {
        return {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
            labelCol2: {
                xs: { span: 24 },
                sm: { span: 3 },
            },
            wrapperCol2: {
                xs: { span: 24 },
                sm: { span: 20 },
            },
            // 新增时子表默认添加几行空数据
            addDefaultRowNum: 1,
            validatorRules: {
                orderNo: {
                    rules: [
                        { required: true, message: '请输入单号!' },
                        { validator: (rule, value, callback) => validateDuplicateValue('plan_production', 'order_no', value, this.model.id, callback) },
                    ]
                },
                productDay: {
                    rules: [
                        { required: true, message: '请输入计划生产日期!' },
                    ]
                },
                startTime: {
                    rules: [
                        { required: true, message: '请输入计划开始时间!' },
                    ]
                },
                endTime: {
                    rules: [
                        { required: true, message: '请输入计划结束时间!' },
                    ]
                },
                needTime: {
                    rules: [
                        { required: true, message: '请输入需求物料时间!' },
                    ]
                },
                productionLine: {
                    rules: [
                        { required: true, message: '请输入所属生产线!' },
                    ]
                },
            },
            refKeys: ['planProductsDetail', 'planPartsDetail',],
            tableKeys: ['planProductsDetail', 'planPartsDetail',],
            activeKey: 'planProductsDetail',
            // 制品明细
            planProductsDetailTable: {
                loading: false,
                dataSource: [],
                columns: [
                    {
                        title: '制品品番',
                        key: 'productsSku',
                        type: FormTypes.select,
                        dictCode: 'basic_products,products_sku,products_sku',
                        width: "200px",
                        placeholder: '请输入${title}',
                        defaultValue: '',
                    },
                    {
                        title: '制品背番',
                        key: 'productsBack',
                        type: FormTypes.select,
                        dictCode: 'basic_products,products_back,products_back',
                        width: "200px",
                        placeholder: '请输入${title}',
                        defaultValue: '',
                    },
                    {
                        title: '生产数量',
                        key: 'number',
                        type: FormTypes.inputNumber,
                        width: "200px",
                        placeholder: '请输入${title}',
                        defaultValue: '',
                    },
                ]
            },
            // 部品明细
            planPartsDetailTable: {
                loading: false,
                dataSource: [],
                columns: [
                    {
                        title: '部品品番',
                        key: 'partsSku',
                        type: FormTypes.input,
                        disabled: true,
                        width: "200px",
                        placeholder: '请输入${title}',
                        defaultValue: '',
                    },
                    {
                        title: '部品背番',
                        key: 'partsBack',
                        type: FormTypes.input,
                        disabled: true,
                        width: "200px",
                        placeholder: '请输入${title}',
                        defaultValue: '',
                    },
                    {
                        title: '箱数',
                        key: 'number',
                        type: FormTypes.inputNumber,
                        width: "200px",
                        placeholder: '请输入${title}',
                        defaultValue: '',
                    },
                    {
                        title: 'EU箱型号',
                        key: 'euType',
                        type: FormTypes.input,
                        disabled: true,
                        width: "200px",
                        placeholder: '请输入${title}',
                        defaultValue: '',
                    },
                    {
                        title: '单箱体积',
                        key: 'volume',
                        type: FormTypes.input,
                        disabled: true,
                        width: "200px",
                        placeholder: '请输入${title}',
                        defaultValue: '',
                    },
                    {
                        title: '总体积',
                        key: 'totalVolume',
                        type: FormTypes.input,
                        disabled: true,
                        width: "200px",
                        placeholder: '请输入${title}',
                        defaultValue: '',
                    },
                    {
                        title: '所属仓库',
                        key: 'warehouseId',
                        type: FormTypes.select,
                        dictCode: 'basic_warehouse,name,id',
                        disabled: true,
                        width: "200px",
                        placeholder: '请输入${title}',
                        defaultValue: '',
                    },
                ]
            },
            url: {
                add: "/planProduction/planProduction/add",
                edit: "/planProduction/planProduction/edit",
                queryById: "/planProduction/planProduction/queryById",
                planProductsDetail: {
                    list: '/planProduction/planProduction/queryPlanProductsDetailByMainId'
                },
                planPartsDetail: {
                    list: '/planProduction/planProduction/queryPlanPartsDetailByMainId'
                },
                getBySku: "/basicProducts/basicProducts/getBySku",
                getByBack: "/basicProducts/basicProducts/getByBack",
            }
        }
    },
    props: {
        //流程表单data
        formData: {
            type: Object,
            default: () => { },
            required: false
        },
        //表单模式：false流程表单 true普通表单
        formBpm: {
            type: Boolean,
            default: false,
            required: false
        },
        //表单禁用
        disabled: {
            type: Boolean,
            default: false,
            required: false
        }
    },
    computed: {
        formDisabled() {
            if (this.formBpm === true) {
                if (this.formData.disabled === false) {
                    return false
                }
                return true
            }
            return this.disabled
        },
        showFlowSubmitButton() {
            if (this.formBpm === true) {
                if (this.formData.disabled === false) {
                    return true
                }
            }
            return false
        }
    },
    created() {
        //如果是流程中表单，则需要加载流程表单data
        this.showFlowData();
    },
    methods: {
        onValueChange(e) {
            if (!e.value) {
                return
            }
            if (e.column.title === '制品品番') {
                getAction(this.url.getBySku + "?sku=" + e.value).then((res) => {
                    if (res.success) {
                        if (e.row.productsBack !== res.result.productsBack) {
                            this.$refs.planProductsDetail.setValues([{
                                rowKey: e.row.id, // 行的id
                                values: { // 在这里 values 中的 name 是你 columns 中配置的 key
                                    'productsBack': res.result.productsBack
                                }
                            }])
                        }
                    } else {
                        this.$message.warning(res.message)
                    }
                })
            } else if (e.column.title === '制品背番') {
                getAction(this.url.getByBack + "?back=" + e.value).then((res) => {
                    if (res.success) {
                        if (e.row.productsSku !== res.result.productsSku) {
                            this.$refs.planProductsDetail.setValues([{
                                rowKey: e.row.id, // 行的id
                                values: { // 在这里 values 中的 name 是你 columns 中配置的 key
                                    'productsSku': res.result.productsSku
                                }
                            }])
                        }

                    } else {
                        this.$message.warning(res.message)
                    }
                })
            }
        },
        addBefore() {
            this.form.resetFields()
            this.planProductsDetailTable.dataSource = []
            this.planPartsDetailTable.dataSource = []
        },
        getAllTable() {
            let values = this.tableKeys.map(key => getRefPromise(this, key))
            return Promise.all(values)
        },
        /** 调用完edit()方法之后会自动调用此方法 */
        editAfter() {
            this.editPlanPartsDetailTableColumns(this.model.status)
            let fieldval = pick(this.model, 'orderNo', 'productDay', 'startTime', 'endTime', 'needTime', 'releaseTime', 'distributionTime', 'productionLine', 'volume', 'remarks')
            this.$nextTick(() => {
                this.form.setFieldsValue(fieldval)
            })
            // 加载子表数据
            if (this.model.id) {
                let params = { id: this.model.id }
                this.requestSubTableData(this.url.planProductsDetail.list, params, this.planProductsDetailTable)
                this.requestSubTableData(this.url.planPartsDetail.list, params, this.planPartsDetailTable)
            }
        },
        /** 整理成formData */
        classifyIntoFormData(allValues) {
            let main = Object.assign(this.model, allValues.formValue)
            return {
                ...main, // 展开
                planProductsDetailList: allValues.tablesValue[0].values,
                planPartsDetailList: allValues.tablesValue[1].values,
            }
        },
        //渲染流程表单数据
        showFlowData() {
            if (this.formBpm === true) {
                let params = { id: this.formData.dataId };
                getAction(this.url.queryById, params).then((res) => {
                    if (res.success) {
                        this.edit(res.result);
                    }
                })
            }
        },
        validateError(msg) {
            this.$message.error(msg)
        },
        popupCallback(row) {
            this.form.setFieldsValue(pick(row, 'orderNo', 'productDay', 'startTime', 'endTime', 'needTime', 'releaseTime', 'distributionTime', 'productionLine', 'volume', 'remarks'))
        },
        editPlanPartsDetailTableColumns(status) {
            if (!status || status == 1) {
                this.$set(this.planPartsDetailTable.columns[3], "type", FormTypes.hidden)
                this.$set(this.planPartsDetailTable.columns[4], "type", FormTypes.hidden)
                this.$set(this.planPartsDetailTable.columns[5], "type", FormTypes.hidden)
            } else {
                this.$set(this.planPartsDetailTable.columns[3], "type", FormTypes.input)
                this.$set(this.planPartsDetailTable.columns[4], "type", FormTypes.input)
                this.$set(this.planPartsDetailTable.columns[5], "type", FormTypes.input)
            }
        }

    }
}
</script>

<style scoped>
</style>